<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8" />
<title>团队详细信息</title>
<meta name="viewport"
	content="width=device-width, initial-scale=1, maximum-scale=1" />

<link href="${mvcPath}/dacp-view/aijs/css/ai.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" href="${mvcPath}/dacp-lib/ztree/zTreeStyle.css" type="text/css">
<style>
.media, .media-body {
	overflow: inherit;
	zoom: 1;
}

.list-group-item.active .dropdown-menu a {
	color: black;
}

small {
	font-size: 9px;
}
.fuelux .wizard {
	border-right: 0px;
	border-bottom: 1px solid #eee;
	box-shadow: 0 0px 0px;
	background-color: transparent;
	box-shadow: none;
	border-radius: 0px;
}

.wrapper {
	padding: 1px 15px 15px 15px;
}

.panel-body {
	padding: 2px 0px 5px 0px;
}
#tab5 .pageContainer{
	display: none;
}
#tab5 table tr{
	border: 1px solid #eee;
}
</style>
<script type="text/javascript"
	src="${mvcPath}/dacp-lib/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="${mvcPath}/dacp-lib/ztree/jquery.ztree.all-3.5.min.js"></script>
<script type="text/javascript"
	src="${mvcPath}/dacp-lib/bootstrap/js/bootstrap.min.js"></script>
	
<script src="${mvcPath}/dacp-lib/cryptojs/aes.js" type="text/javascript"></script>
<script src="${mvcPath}/crypto/crypto-context.js" type="text/javascript"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.core.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.field.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.jsonstore.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.grid.js"></script>
<script src="${mvcPath}/dacp-lib/underscore/underscore-min.js"></script>
<script src="${mvcPath}/dacp-view/aijs/js/ai.treeview.js"> </script>
 <script src="${mvcPath}/dacp-res/catalog/common/js/ai.meta.widget.js"></script>
<style>
.media, .media-body {
	overflow: inherit;
	zoom: 1;
}

.list-group-item.active .dropdown-menu a {
	color: black;
}

small {
	font-size: 9px;
}
 
.wrapper {
	padding: 1px 15px 15px 15px;
}
 
a.plan {
	font-size: 14px;
}

a.task {
	font-size: 13px;
}

.toolbar {
	margin-top: 10px;
	margin-bottom: 10px;
}

.toolbar .form-control {
	display: inline;
	padding: 1px 2px;
}

.toolbar button {
	margin-left: 10px;
}
.panel .table-striped > thead th {
    background-color: #36B0C8;
}
.ztree .line {
	height: auto;
}
.aui_content{
	overflow-y:auto;
	overflow-x:hidden;
}
.form-horizontal{
	overflow: hidden !important;
}
.form-group {
    margin-bottom: 9px !important;
}
#team_flow_member .pull-right:link { 
	color: #036; text-decoration: none; 
}
#team_flow_member .pull-right:hover{
	color: #F90; text-decoration: none;background: #c9cbce;
}
#team_flow_member .pull-right{
	cursor: pointer;
}
.empty{
	border-bottom: none;
	font-size: 14px;
	font-style: italic;
	padding: 20px;
	text-align: center;
	width: 100%;
}
</style>
<script>
TeamPerMission={
	ruleTreeGrid:null,
	treesql:"SELECT TEAM_CODE, RULE_CODE, PARENTCODE, RULETYPE, RULENAME, RULETEXT, DBNAME, TOPICNAME, REMARK FROM meta_team_permission where team_code='{team_code}' and rule_code like 'R01%' order by rule_code",
	config : {
		id : "metaTeamPerssionInfo",
		width : "800",
		renderTo : "metaTeamPerssionInfo",
		headerAlign : "left",
		headerHeight : "30",
		dataAlign : "left",
		indentation : "8",
		hoverRowBackground : "true",
		folderColumnIndex : "0",
		itemClick : this.itemClickEvent,
		//showcheck:true,
		columns : [ 
			
			{headerText : "名称", dataField : "RULENAME", headerAlign : "center", width : "220", dataAlign : "center",handler:this.ruleNameRender}, 
			{headerText : "操作", dataField : "ACT", headerAlign : "center", width : "150", dataAlign : "center" ,handler:this.actRender},
			{headerText : "规则编号", dataField : "RULE_CODE", headerAlign : "center", width : "220" }, 
			{headerText : "备注", dataField : "REMARK", headerAlign : "center", dataAlign : "center", width : "320"}
			// ,{headerText : "规则描述", dataField : "REMARK", headerAlign : "center", width : "320", dataAlign : "center" }
		],
		keyfield : "RULE_CODE",
		pkeyfield : "PARENTCODE",
		titlefield : "RULENAME",
		iconfield : "",
		store:null,
		subtype : 'treegrid'
	},
	itemClickEvent:function(id, index, data) {
	   //console.log( id + ", " + index + ", " 	+ TreeGrid.json2str(data));
	   // console.log(TeamPerMission.ruleTreeGrid.getSelectedItem());
	},
	ruleNameRender:function(row, col){
		if(!row.PARENTCODE) return '<b>'+row.RULENAME+'<b> '
		else return row.RULENAME ;
	},
	remarkRender:function(row, col){
		if(row.REMARK && row.REMARK.length>40) return row.REMARK.substr(1,40)+'.... '
		else return row.REMARK ;
	},
	actionItems:{
		synatic:{title:'同步数据库',icon:'glyphicon glyphicon-refresh'},
		pickdbTopic:{title:'选择主题',icon:'glyphicon glyphicon-zoom-in'},
		addTeamTopic:{title:'增加主题',icon:'glyphicon glyphicon-plus'},
		add:{title:'增加',icon:'glyphicon glyphicon-plus'},
		del:{title:'删除',icon:'glyphicon glyphicon-remove'},
		edit:{title:'编辑',icon:'glyphicon glyphicon-pencil'}
	},
	deleteRule:function(){
		var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
		var rulecode = curItem.data.RULE_CODE;
		var dbname = curItem.data.DBNAME;

		var num = ai.getStoreData("select count(1) num from meta_team_permission where team_code = '" + this.teamcode + "' and dbname = '" + dbname + "' and parentcode = '" + rulecode + "'")[0].NUM;
		if(num && num>0) {
			alert("请先删除子节点！");
			return false;
		}

		var r=this.config.store.getRecordByKey(this.teamcode+","+rulecode);

		if(window.confirm("确定删除:"+r.get('RULENAME')+"吗?")){
			this.config.store.remove(r);
			this.config.store.commit();
			this.reset(this.options);
		}
	},
	addRule:function(){
		var ruleObj =null;
	  	var aftSave=function(fieldVals) {
			var newRuelCode = ai.getNewCode(TeamPerMission.config.store,"RULE_CODE",curItem.data.RULE_CODE+"-");//store,fieldname,pre,tabname
			var ruleText = ai.toJSON(ruleObj);
			var r=TeamPerMission.config.store.getNewRecord();
			r.set('TEAM_CODE',TeamPerMission.teamcode);
			r.set('RULE_CODE',newRuelCode);
			r.set('PARENTCODE',curItem.data.RULE_CODE);
			r.set('RULETYPE','rule');
			r.set('RULENAME',ruleObj.RULENAME+"("+ruleObj.RIGTHLEVEL+")");
			r.set('RULETEXT',ruleText);
			r.set('REMARK',ruleText);
			TeamPerMission.config.store.add(r);
			TeamPerMission.config.store.commit();
			TeamPerMission.reset(TeamPerMission.options);
	  	};
	  	var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	var rulecode = curItem.data.RULE_CODE;
	  	var r=this.config.store.getRecordByKey(this.teamcode+","+rulecode);
	  	this.config.store.curRecord=r;
	  	
	  	var ruleText = r.get('RULETEXT')||"{}";
	  	ruleObj = jQuery.parseJSON(ruleText)||{};
	  	
	  	var useRigthRuleForm = ({
			id : 'form',
			items : [
				{ type : 'text', label : '规则名称', fieldName : 'RULENAME', width : 220},
				{ type : 'html', html : '<hr>', fieldName : 'TEAM_CODE', width : 220},
				{ type : 'pick-grid', label : '开发团队', fieldName : 'TEAM_CODE',storesql:"select TEAM_CODE VALUES1,TEAM_NAME VALUES2 from meta_team where TEAM_CODE<>'"+this.teamcode+"'", width : 220},
				{ type : 'checkbox', label : '数据库', fieldName : 'DBNAME',storesql:"select dbname,CNNAME from metadbcfg where dbname<>'METADB'", width : 420  },
				{ type : 'text', label : '主题包含', fieldName : 'TOPICCODE', width : 220  } ,
				{ type : 'text', label : '表名包含', fieldName : 'OBJNAME', width : 220  } ,
				{ type : 'checkbox', label : '权限级别', fieldName : 'RIGTHLEVEL',storesql:'一级敏感,二级敏感,普通', width : 220  },
				{ type : 'html', html : '<hr>', fieldName : 'TEAM_CODE', width : 220},
				{ type : 'combox', label : '<b>授权类型</b>', fieldName : 'RIGTHLEVEL', storesql:'免授权,申请授权,不允许申请',width : 220  },
			],
			fieldChange:function(fieldName, newVal){ 
				console.log(fieldName,newVal);
				ruleObj[fieldName]=newVal;
			}
		});
		for(var i=0;i<useRigthRuleForm.items.length;i++){
			var item = useRigthRuleForm.items[i];
			if(ruleObj[item.fieldName]) item.value=ruleObj[item.fieldName];
		}
		ai.showDialogForm(useRigthRuleForm,null,aftSave);
	  },
	  editRule:function(){
	  	var ruleObj =null;
	  	var aftSave=function(fieldVals){
			console.log(_global_from.fields);

			var ruleText = ai.toJSON(ruleObj);
			TeamPerMission.config.store.curRecord.set('RULETEXT',ruleText);
			TeamPerMission.config.store.curRecord.set('RULENAME',ruleObj.RULENAME+"("+ruleObj.RIGTHLEVEL+")");
			TeamPerMission.config.store.commit();
			TeamPerMission.reset(TeamPerMission.options);
	  	};
	  	var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	var rulecode = curItem.data.RULE_CODE;
	  	var r=TeamPerMission.config.store.getRecordByKey(this.teamcode+","+rulecode);
	  	this.config.store.curRecord=r;
	  	
	  	var ruleText = r.get('RULETEXT')||"{}";
	  	ruleObj = jQuery.parseJSON(ruleText)||{};
	  	
	  	var useRigthRuleForm = ({
			id : 'form',
			items : [
				{ type : 'text', label : '规则名称', fieldName : 'RULENAME', width : 220},
				{ type : 'html', html : '<hr>', fieldName : 'TIP1', width : 220},
				{ type : 'pick-grid', label : '开发团队', fieldName : 'TEAM_CODE',storesql:"select TEAM_CODE VALUES1,TEAM_NAME VALUES2 from meta_team where TEAM_CODE<>'"+this.teamcode+"'", width : 220},
				{ type : 'checkbox', label : '数据库', fieldName : 'DBNAME',storesql:"select dbname,CNNAME from metadbcfg where dbname<>'METADB'", width : 420  },
				{ type : 'text', label : '主题包含', fieldName : 'TOPICCODE', width : 220  } ,
				{ type : 'text', label : '表名包含', fieldName : 'OBJNAME', width : 220  } ,
				{ type : 'checkbox', label : '权限级别', fieldName : 'RIGTHLEVEL',storesql:'一级敏感,二级敏感,普通', width : 220  },
				{ type : 'html', html : '<hr>', fieldName : 'TIP2', width : 220},
				{ type : 'combox', label : '<b>授权类型</b>', fieldName : 'RIGTHLEVEL', storesql:'免授权,申请授权,不允许申请',width : 220  }
			],
			fieldChange:function(fieldName, newVal){ 
				ruleObj[fieldName]=newVal;
			}
		});
		for(var i=0;i<useRigthRuleForm.items.length;i++){
			var item = useRigthRuleForm.items[i];
			if(ruleObj[item.fieldName]) item.value=ruleObj[item.fieldName];
		};
		ai.showDialogForm(useRigthRuleForm,null,aftSave);
	  },
	  editToolsCfg:function(tooltype){
	  	var aftSave=function(fieldVals){
			var reamrk =_global_from.fields[2].getRawValue();
			TeamPerMission.config.store.curRecord.set('RULETEXT',selVal);
			TeamPerMission.config.store.curRecord.set('REMARK',reamrk||selVal );
			TeamPerMission.config.store.commit();
			TeamPerMission.reset(TeamPerMission.options);
	  	};
		var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	var rulecode = curItem.data.RULE_CODE;
	  	var r=TeamPerMission.config.store.getRecordByKey(this.teamcode+","+rulecode);
	  	this.config.store.curRecord=r;
	  	var selVal=r.get('RULETEXT');
	  	var toolForm = ({
			id : 'form',
			title:'选择工具',
			items : [
				{ type : 'html', html : '选择工具' },
				{ type : 'html', html : '<hr>' },
				{ type : 'checkbox', label : ' ', fieldName : 'TOOLS',value:selVal, storesql:"select SOFTSYSCODE,SYSTEM_NAME from metasoftcfg where TYPE='"+tooltype+"'", 
				  width : 420  }
			],
			fieldChange:function(fieldName, newVal){ 
				selVal=newVal;
				//ruleObj[fieldName]=newVal;
			}
		});
		 
		ai.showDialogForm(toolForm,null,aftSave);
	  },
	  actFun:function(actId){
	  	 var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	 if(actId=="synatic") this.reset(this.options, true);
	  	 else if(actId=="pickdbTopic")  this.selectDbTopic("",this.afterSelectDbTopic);
	  	 else if(actId=="addTeamTopic") this.addTeamTopic(this.teamcode);
	  	 else if(actId=="add")  this.addRule("add");
	  	 else if(actId=="del")  this.deleteRule();
	  	 else if(actId=="edit" &&(curItem.data.RULETYPE=="prodtools"|| curItem.data.RULETYPE=="mgrtools"))  this.editToolsCfg(curItem.data.RULETYPE);
	  	 else  if(actId=="edit")  this.editRule("edit");
	  },
	  afterSelectDbTopic:function(curItem,topicArray){
	  	console.log(topicArray);
	  //	var curItem = this.ruleTreeGrid.getSelectedItem();
	  	var rulecode = curItem.data.RULE_CODE;
	  	
	  	function checkTopicExists(topicCode){
			var result=false;
			var childrenArray = curItem.getChildren();
			for(var i=0;i<childrenArray.length;i++){
				if(childrenArray[i].TOPICNAME==topicCode){
					result=true;
					break;
				}
			}
			return result;
	  	};
	  	
	  	for(var i=0;i<topicArray.length;i++){
	  		
			var addTopicCode=topicArray[i].RULECODE;

			if(checkTopicExists(addTopicCode)==true) continue;
			// var newRuelCode = ai.getNewCode(TeamPerMission.config.store,"RULE_CODE",curItem.data.RULE_CODE+"-");//store,fieldname,pre,tabname

			var parentCode = topicArray[i].PARENTCODE;
			if(!parentCode) parentCode = curItem.data.RULE_CODE
			else parentCode=curItem.data.RULE_CODE+"-"+parentCode;

			var r=TeamPerMission.config.store.getNewRecord();
			r.set('TEAM_CODE',TeamPerMission.teamcode);
			r.set('RULE_CODE',curItem.data.RULE_CODE+"-"+topicArray[i].RULECODE);
			r.set('PARENTCODE',parentCode);
			r.set('RULETYPE','topic');
			r.set('RULENAME',topicArray[i].RULENAME );
			r.set('DBNAME',topicArray[i].DBNAME );
			r.set('TOPICNAME',topicArray[i].RULECODE );
			r.set('RULETEXT',topicArray[i].FUNC_ID);
			r.set('REMARK',topicArray[i].DBNAME+","+topicArray[i].RULENAME);
			TeamPerMission.config.store.add(r);
         		
	  	};
	  	TeamPerMission.config.store.commit();
        TeamPerMission.reset(this.options);
	  },
	  actRender:function(row,col){
	  	 var actnameArray="";
	  	 var ruleCode=row.RULE_CODE;
	  	 if(ruleCode=='R09') return "";
	  	 
	  	 if(row.RULETYPE=='database') actnameArray=['pickdbTopic','addTeamTopic'/*,'del'*/]
	  	 else  if(row.RULETYPE=='ownertopic') actnameArray=['synatic'] 
	  	 else if(ruleCode=='R01') actnameArray=''
	  	 else if(ruleCode=='R02' || ruleCode=='R03' ||ruleCode=='R04') actnameArray=['add']
	  	 else   actnameArray=[/* 'edit', */'del','addTeamTopic'];
	  	  var html="";
	     if(actnameArray){
	     	 for(var i=0;i<actnameArray.length;i++){
	     	 	 var actid=actnameArray[i];
	     	 	 var actItem = TeamPerMission.actionItems[actid];
	     	 	 html+='<a id="'+actid+'" href="#" class="ruleact"><span class="'+actItem.icon+'"></span>'+actItem.title+'</a>&nbsp;&nbsp;'
	     	};
	    };
	    return html;
	  },
	  selectDbTopic:function(selsql,callback){
	  	var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	var dbname = curItem.data.DBNAME;
	 	  art.dialog({
   				 title: '数据库主题选择:'+curItem.data.DBNAME,
    				width: 860,height:300,
    				content: '<div style="height:300px;overflow:auto;" id="selecdbtopic"></div>',
    				 init: function () {
     							//buildMetaTeamPerssion();
    				},
    				ok: function () {
    					var selDataArray=seltreeGrid.getAllCheck();
    					if(selDataArray.length==0) {alert('你没有选择记录');return false;};
    					if(callback) return callback(curItem,selDataArray);
        				return true;
   					 },
   					 cancel:function(){
   					}
			});
			 selsql="select DBNAME,RULECODE,RULENAME,PARENTCODE,RULETYPE,FUNC_ID,FUNC_NAME,RULEDEF from metadb_struct where DBNAME ='"+dbname+"'";
	 		var dbStrutStore=  new AI.JsonStore({
                sql:selsql.replace('{teamcode}',this.teamcode),
                key:"DBNAME,RULECODE",
                pageSize:-1,
                table:"METADB_STRUCT"  
        	});
      		var config = {
				id : "selecdbtopic",
				width : "800",
				renderTo : "selecdbtopic",
				headerAlign : "left",
				headerHeight : "30",
				dataAlign : "left",
				indentation : "8",
				hoverRowBackground : "true",
				folderColumnIndex : "0",
				showcheck:true,
				columns : [ 
					{headerText : "主题编号", dataField : "RULECODE", headerAlign : "center", width : "180" }, 
					{headerText : "数据库名", dataField : "DBNAME", headerAlign : "center", width : "120" },
					{headerText : "主题名称", dataField : "RULENAME", headerAlign : "center", width : "120", dataAlign : "center", width : "100"}
				],
				keyfield : "RULECODE",
				pkeyfield : "PARENTCODE",
				titlefield : "RULENAME",
				iconfield : "",
				store:dbStrutStore,
				subtype : 'treegrid'
			};
           var seltreeGrid = new TreeGrid(config);
           seltreeGrid.show();
	 },
	 addTeamTopic: function(teamcode) {
	 	var curItem = TeamPerMission.ruleTreeGrid.getSelectedItem();
	  	var dbname = curItem.data.DBNAME;
	  	var parentcode = curItem.data.RULE_CODE;
	  	var parenttype = curItem.data.RULETYPE;
	  	var parentTopicCode = curItem.data.TOPICNAME;

	 	var teamTopicStore =  new AI.JsonStore({
            sql: "SELECT * FROM META_TEAM_PERMISSION WHERE TEAM_CODE = '" + this.teamcode + "'",
            key: "TEAM_CODE,RULE_CODE,DBNAME",
            pageSize: -1,
            table: "META_TEAM_PERMISSION"  
    	});
	 	var items = [
			// {type:'text',label:'规则编号',fieldName:'RULE_CODE',notNull:'N',width:320},
			// {type:'text',label:'上级编码',fieldName:'PARENTTOPICCODE',width:320,isReadOnly: "y"},
			// {type:'combox',label:'节点类型',fieldName:'RULETYPE',notNull:'N',storesql:'LEVELVAL,层次|topic,主题',width:320},
			{type:'text',label:'主题编码',fieldName:'TOPICNAME',notNull:'N',width:320},
			{type:'text',label:'中文名',fieldName:'RULENAME',notNull:'N',width:320},
			{type:'checkbox',label:'可包含对象',fieldName:'RULETEXT',storesql:"select OBJTYPE,OBJNAME from METAOBJMODEL where PARENTCODE is not null and parentcode<>'META-OTHER' and parentcode<>'META' and STATE = 'Y' order by ORDSEQ asc ",width:320},
			{type:'textarea',label:'备注',fieldName:'REMARK',width:420} 
		];

	   	var addTeamTopicCallBack = function() {
	   		var ruletext = "";
	   		var rulecode = "";
		   	
			var topicname = $("#TOPICNAME").val();
			var rulename = $("#RULENAME").val();
			var ruletype = "topic";
			var remark = $("#REMARK").val();

			var prefix = parentTopicCode + "_";

			if(parenttype != "database" && !new RegExp("^" + prefix).test(topicname)) {
				alert("该目录的主题编码应以" + prefix + "为前缀！请重新输入");
				$("#TOPICNAME").val(prefix);
				return false;
			}

			var str=document.getElementsByName("RULETEXT");
			for(var i=0;i<str.length;i++){
				if(str[i].checked){
					ruletext += str[i].value + ",";
				}
			}
			ruletext = ruletext.substring(0, ruletext.lastIndexOf(","));

			var getRuleCode = function(parentcode, topicname) {
				var pre = "R01-";
				if(parenttype == "database") {
					return parentcode + "-" + topicname;
				}
				var temp = parentcode.replace("R01-", "");
				var dbNum = temp.substring(0, temp.indexOf("-"));
				return pre + dbNum + "-" + topicname;
			};
			rulecode = getRuleCode(parentcode, topicname);

			var rec = teamTopicStore.getNewRecord();
			rec.set("TEAM_CODE", teamcode);
		   	rec.set("DBNAME", dbname);
		   	rec.set("RULE_CODE",rulecode);
		   	rec.set("PARENTCODE",parentcode);
		   	rec.set("RULENAME",rulename);
		   	rec.set("RULETYPE","topic");
		   	rec.set("RULETEXT",ruletext);
		   	rec.set("TOPICNAME",topicname);
		   	rec.set("REMARK",remark);
		   	//校验当前编号是否按照规则
		   	if(rulecode && rulename && ruletype && topicname && ruletext){
	   			var oldStructDataStoreSql = "SELECT * FROM META_TEAM_PERMISSION WHERE TEAM_CODE = '" + teamcode + "' AND DBNAME = '" + dbname + "'";
	   			var oldStructDataStore = new AI.JsonStore({
	   				sql:oldStructDataStoreSql,
	                key:"TEAM_CODE,RULE_CODE,DBNAME",
	                pageSize:-1,
	                table:"META_TEAM_PERMISSION"
	   			});
	   			var isExist = oldStructDataStore.getRecordByKey(teamcode + "," + rulecode + "," + dbname);
		   		if(isExist){
		   			alert("当前编码已存在");
		   			return false;
		   		}

		   		var _index = rulecode.lastIndexOf("-");
		   		var codePre = rulecode.substr(0,_index);
		   		var codeEnd = rulecode.substr(_index+1,rulecode.length);
		   	}else{
		   		alert("请填写带\" * \"的必填项！");
				return false;
		   	}
	   		teamTopicStore.add(rec);
		   	teamTopicStore.commit();
		   	TeamPerMission.reset(this.options);
		}
	 	ai.openFormDialog("新增团队主题",items,addTeamTopicCallBack,null);
	 	// $("#PARENTCODE").val(parentcode);
	 	// $("#RULE_CODE").val(parentcode + "-");
	 	if(parenttype != 'database') {
	 		$("#TOPICNAME").val(parentTopicCode + "_");
	 	}
	 },
	 bindEvent:function(){
	 	
	 	$("#metaTeamPerssionInfo table tr td a.ruleact").click(function(event){
			$(this).parent().parent().click();
			var actId = $(this).attr("id");
			
			 event.stopPropagation();
			 TeamPerMission.actFun(actId);
			
			 return false;
		});
	},
	  init:function(options){
	  	 this.options=options;
	     this.teamcode=options.teamcode;

	     var editable = options.editable;

	     if(editable) {
	     	this.config.columns = [ 
				{headerText : "名称", dataField : "RULENAME", headerAlign : "center", width : "220", dataAlign : "center",handler:this.ruleNameRender}, 
				{headerText : "操作", dataField : "ACT", headerAlign : "center", width : "190", dataAlign : "center" ,handler:this.actRender},
				{headerText : "规则编号", dataField : "RULE_CODE", headerAlign : "center", width : "220" }, 
				{headerText : "备注", dataField : "REMARK", headerAlign : "center", dataAlign : "center", width : "320"}
			]
	     } else {
	     	this.config.columns = [ 
				{headerText : "名称", dataField : "RULENAME", headerAlign : "center", width : "220", dataAlign : "center",handler:this.ruleNameRender}, 
				{headerText : "规则编号", dataField : "RULE_CODE", headerAlign : "center", width : "220" }, 
				{headerText : "备注", dataField : "REMARK", headerAlign : "center", dataAlign : "center", width : "320"}
			]
	     }

	     var dbStrutStore=  new AI.JsonStore({
                  sql:this.treesql.replace("{team_code}",options.teamcode),
                  key:"TEAM_CODE,RULE_CODE",
                  pageSize:-1,
                  table:"meta_team_permission"  
         });
        if(dbStrutStore.getCount()==0){
         
        	var r=dbStrutStore.getNewRecord();
        	r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R01');r.set('RULETYPE','ownertopic');r.set('RULENAME','工作目录主题');
        	dbStrutStore.add(r);
        	
        	// var r=dbStrutStore.getNewRecord();
        	// r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R02');r.set('RULETYPE','datauserrule');r.set('RULENAME','同库数据使用权限规则');
        	// dbStrutStore.add(r);
        	
        	// var r=dbStrutStore.getNewRecord();
        	// r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R03');r.set('RULETYPE','datasendrule');r.set('RULENAME','跨库分发使用的规则');
        	// dbStrutStore.add(r);
        	
        	// var r=dbStrutStore.getNewRecord();
        	// r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R04');r.set('RULETYPE','dataopenrule');r.set('RULENAME','数据服务平台使用规则');
        	// dbStrutStore.add(r);
        	
        	// var r=dbStrutStore.getNewRecord();
        	// r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R09');r.set('RULETYPE','tools');r.set('RULENAME','开通工具');
        	// dbStrutStore.add(r);
        	
        	// var r=dbStrutStore.getNewRecord();
        	// r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R09-01');r.set('PARENTCODE','R09');r.set('RULETYPE','prodtools');r.set('RULENAME','开发工具');
        	// dbStrutStore.add(r);
        	// var r=dbStrutStore.getNewRecord();
        	// r.set('TEAM_CODE',this.teamcode);r.set('RULE_CODE','R09-02');r.set('PARENTCODE','R09');r.set('RULETYPE','mgrtools');r.set('RULENAME','管理工具');
        	dbStrutStore.add(r);
        	dbStrutStore.commit();
        };
         $("#metaTeamPerssionInfo").empty();

         this.config.store=dbStrutStore;
         this.config.itemClick=this.itemClickEvent;
         this.config.columns[0].handler = this.ruleNameRender;
         // this.config.columns[1].handler = this.actRender;
         this.config.columns[2].handler = this.remarkRender;
		this.ruleTreeGrid = new TreeGrid(this.config);
		this.ruleTreeGrid.show();
        this.bindEvent();
      },
	reset:function(options, isFromSyncButton){
      	if(!isFromSyncButton) {
      		this.init(this.options);
      		return;
      	}
      	//同步数据库
      	var self = this;
      	var sql = "select DBNAME VALUES1, CNNAME VALUES2, TEAM_CODE VALUES3 from DATA_TRANS_DATABASE where TEAM_CODE = '" + this.teamcode + "' and dbname not in (select DBNAME from META_TEAM_PERMISSION where TEAM_CODE = '" + this.teamcode + "' and ruletype = 'database')";
      	if(ai.getJsonStore(sql).getCount() == 0) {
      		alert("没有需要同步的数据库");
      		return;
      	}
      	var afterSelect = function(rs) {
      		if(rs.length == 0) {
      			alert("请至少选择一个需要同步的数据库！");
      			return false;
      		}
      		for(var i in rs) {
      			var r = rs[i];
      			var newRuelCode = ai.getNewCode(self.config.store,"RULE_CODE",'R01-');//store,fieldname,pre,tabname
				var newRec = self.config.store.getNewRecord();
				newRec.set('TEAM_CODE',self.teamcode);
				newRec.set('RULE_CODE',newRuelCode);
				newRec.set('PARENTCODE','R01');
				newRec.set('RULETYPE','database');
				newRec.set('RULENAME',r.get('VALUES1'));
				newRec.set('RULENAME',r.get('VALUES2')); 
				newRec.set('DBNAME',r.get('VALUES1')); 
				self.config.store.add(newRec);
      		}
      		self.config.store.commit();
      		self.init(self.options);
      	};
      	var selBox=new SelectBox({sql:sql, callback:afterSelect});
		selBox.show();
      	/*
		for(i=0;i<ds_teamdb.getCount();i++){
			var r=ds_teamdb.getAt(i);
			var exitst=false;
			for(var j=0;j< this.config.store.getCount();j++){
				var structRec = this.config.store.getAt(j);
				if(structRec.get('PARENTCODE')!='R01') continue;
				if(structRec.get('DBNAME')==r.get('DBNAME')){
					exitst=true;
				}
			};
			if(exitst==false){
				var newRuelCode = ai.getNewCode(this.config.store,"RULE_CODE",'R01-');//store,fieldname,pre,tabname
				var newRec = this.config.store.getNewRecord();
				newRec.set('TEAM_CODE',this.teamcode);
				newRec.set('RULE_CODE',newRuelCode);
				newRec.set('PARENTCODE','R01');
				newRec.set('RULETYPE','database');
				newRec.set('RULENAME',r.get('DBNAME'));
				newRec.set('RULENAME',r.get('CNNAME')); 
				newRec.set('DBNAME',r.get('DBNAME')); 
				this.config.store.add(newRec);
			};
		}
      	this.config.store.commit();
      	this.init(this.options);
		*/
	}	
};

$(document).ready(function(){
	ai.loadWidget("dialog");
	
	var objtype="TEAM";
	var teamXmlid = paramMap.xmlid;
	var objname=paramMap.objname||'T001';
	var isMgr = (function() {
		var username = _UserInfo.username;
		var count = ai.getStoreData("select count(1) num from meta_team_role_user where team_code = '" + objname + "' and username = '" + username + "' and role_code = 'teamMgr'")[0].NUM;
		if(count > 0) {
			return true;
		}
		return false;
	})();
 
	var metasoft=new AI.Meta(objtype);

	function buildMetaBaseInfo(){
 		var objAttrStore=ai.getStoreData("select * from metaobjcfg where objtype='"+objtype+"' order by seq");
 		objDataStore=ai.getStoreData("select * from meta_team where team_code='"+objname+"'");
 		console.log(objAttrStore);
 		var html = '<fieldset> <table class="table"> <tbody>';
 		var objdbRec=objDataStore[0];
 		for(var i=0;i<objAttrStore.length;i++){
 			var objAttrItem = objAttrStore[i];
 			html+='<tr > <th class="strong w-80px"> '+objAttrItem.ATTRCNNAME.replace("租户","团队")+'</th><td>'+objdbRec[objAttrItem.ATTRNAME]||""+' </td></tr>';
 		};
         html+='</tbody></table></fieldset>';              
         $("#teambaseinfo").empty().append(html);     
 	};
	 	///构建团队角色信息
 	function buildTeamRoleList(){
		$("#teamrolelist").empty();
		var htmltpl='<a rolecode="{rolecode}" data-name="{rolename}" class="list-group-item"> <i class="icon-users icon text-warning"></i> {rolename}, {rolecode} </a>';
		var html="";
 
		teamRoleStore = new AI.JsonStore({
			sql :"select TEAM_CODE,ROLE_CODE,ROLE_NAME,ROLE_REMARK from meta_team_role where TEAM_CODE='"+objname+"'",
			table:'meta_team_role',
			key:'TEAM_CODE,ROLE_CODE',
			pageSize : -1
		});
		if(teamRoleStore.getCount()==0){
			var r=teamRoleStore.getNewRecord();
			r.set('TEAM_CODE',objname);
			r.set('ROLE_CODE',"teamMgr");
			r.set('ROLE_NAME',"团队管理");
			r.set('ROLE_REMARK',"负责团队的管理工作");
			teamRoleStore.add(r);

			r=teamRoleStore.getNewRecord();
			r.set('TEAM_CODE',objname);
			r.set('ROLE_CODE',"teamWfDeveloper");
			r.set('ROLE_NAME',"开发角色");
			r.set('ROLE_REMARK',"负责开发的工作");
			teamRoleStore.add(r);

			// r=teamRoleStore.getNewRecord();
			// r.set('TEAM_CODE',objname);
			// r.set('ROLE_CODE',"teamWfAuditer");
			// r.set('ROLE_NAME',"审批角色");
			// r.set('ROLE_REMARK',"负责审批的工作");
			// teamRoleStore.add(r);

			// r=teamRoleStore.getNewRecord();
			// r.set('TEAM_CODE',objname);
			// r.set('ROLE_CODE',"teamWfOnliner");
			// r.set('ROLE_NAME',"上线角色");
			// r.set('ROLE_REMARK',"负责上线的工作");
			// teamRoleStore.add(r);

			teamRoleStore.commit();
		}

		r=teamRoleStore.getNewRecord();
		r.set('TEAM_CODE',objname);
		r.set('ROLE_CODE',"all");
		r.set('ROLE_NAME',"团队成员列表");
		r.set('ROLE_REMARK',"全部团队成员");
		teamRoleStore.add(r);

		for (var i = 0; i < teamRoleStore.getCount(); i++) {
			var r=teamRoleStore.getAt(i);
			html+=htmltpl.replace("{rolecode}",r.get('ROLE_CODE')).replace("{rolecode}",r.get('ROLE_CODE')).replace("{rolename}",r.get('ROLE_NAME')).replace("{rolename}",r.get('ROLE_NAME'));
		}
		$("#teamrolelist").append(html);
		$("#teamrolelist .list-group-item").click( function() {
			$("#teamrolelist .list-group-item").removeClass("active");
			$(this).addClass("active");
		 
			teamRoleCode=$(this).attr("rolecode");
			teamRoleStore.curRecord=teamRoleStore.getRecordByKey(objname+","+teamRoleCode);
			var teamName=$(this).attr("rolename");

			if(teamRoleCode == "all") {
				$("#selectteamuser").hide();
			} else {
				$("#selectteamuser").show();
			}

			buildTeamUserList();
			return false;
		});
 		$("#teamrolelist .list-group-item")[0].click();
	
		// $("#delTeamRole").click(function(){
		// 	var r=teamRoleStore.curRecord;
		// 	if(window.confirm("确定删除团队角色:"+r.get('ROLE_NAME')+"吗?")){
		// 		teamRoleStore.remove(r);
		// 		teamRoleStore.commit();
		// 		var sql="delete from meta_team_role_user where ROLE_CODE ='"+r.get('ROLE_CODE')+"' and team_code='"+objname+"'";
		// 		ai.executeSQL(sql);		
				
		// 		alert('成功删除');
		// 		buildTeamRoleList();
		// 	};
		// });
	
		// $("#addTeamRole").click(function(){
		// 	   var aftSave=function(fieldVals){
		// 	   	  var r=teamRoleStore.getNewRecord();
		// 	   	  r.set('TEAM_CODE',objname);
		// 	   	  r.set('ROLE_CODE',fieldVals.ROLE_CODE);
		// 	   	  r.set('ROLE_NAME',fieldVals.ROLE_NAME);
		// 	   	   r.set('ROLE_REMARK',fieldVals.ROLE_REMARK);
		// 	   	   teamRoleStore.add(r);
		// 	   	   teamRoleStore.commit();
		// 	   	   buildTeamRoleList();
		// 	  };
		// 	    var teamRoleForm = ({
		// 			id : 'form',
					 
		// 			items : [ { type : 'text', label : '角色名',notNull:'N', fieldName : 'ROLE_CODE', width : 220},
		// 				{ type : 'text', label : '中文名', notNull:'N',fieldName : 'ROLE_NAME', width : 220  } ,
		// 				{ type : 'textarea', label : '备注', fieldName : 'ROLE_REMARK', width : 420  } 
		// 			],
		// 			fieldChange:function(fieldName, newVal){ }
		// 		});
		//      ai.showDialogForm(teamRoleForm,null,aftSave);
	 //    });
		 
		// $("#editTeamRole").click(function() {
		// 	var teamRoleForm = ({
		// 			id : 'formaaa',
		// 			store : teamRoleStore,     
		// 			items : [ { type : 'text', label : '角色名',notNull:'N', fieldName : 'ROLE_CODE', width : 220,isReadOnly:true},
		// 				{ type : 'text', label : '中文名', notNull:'N',fieldName : 'ROLE_NAME', width : 220  } ,
		// 				{ type : 'textarea', label : '备注', fieldName : 'ROLE_REMARK', width : 420  } 
		// 			],
		// 			fieldChange:function(fieldName, newVal){ }
		// 		});
		// 		ai.showDialogForm(teamRoleForm,null,null);
		// });

	}

 	function buildTeamUserList(){
 		$("#teamuserinfo").empty();
 		var html = '<li class="list-group-item" USERNAME="{USERNAME}" style="min-height: 66px">'
			+ '<a class="thumb-sm pull-left m-r-sm" style="font-size:30px"> <span class="glyphicon glyphicon-user img-circle" aria-hidden="true"></span></a>'
			+ '<a class="clear"> <small class="pull-right"> <b> {USERROLE} </b></small>  '
			+ '<strong class="block">{USECNNAME}, {USERNAME} </strong> '
			+ '<small>{REMARK}{DBUSER}{PHONE}{MAIL} </small></a>'
			+ '</li>';
		var rolecode=teamRoleStore.curRecord.get('ROLE_CODE');	
		var userSql="select a.TEAM_CODE,a.ROLE_CODE, a.REMARK,b.USERNAME,b.USECNNAME ,PHONE,MAIL,DBUSER from meta_team_role_user a ,metauser b where a.username=b.username and a.team_code ='{teamcode}'  and a.role_code='"+rolecode+"' ";
		if(rolecode == "all") {
			userSql = "select distinct a.TEAM_CODE, '' ROLE_CODE, a.REMARK,b.USERNAME,b.USECNNAME ,PHONE,MAIL,DBUSER from meta_team_role_user a ,metauser b where a.username=b.username and a.team_code ='{teamcode}'";
		}
		ds_teamUser = new AI.JsonStore({
			sql :userSql.replace('{teamcode}', objname),
			table:'meta_team_role_user',
			key:'TEAM_CODE,ROLE_CODE,USERNAME',
			pageSize : -1
		});
		
		for(var i=0;i<ds_teamUser.getCount();i++){
			var r=ds_teamUser.getAt(i);
			var newHtml = html.replace("{USERROLE}",r.get("ROLE_CODE") )
				.replace("{USERNAME}",r.get("USERNAME")).replace("{USERNAME}",r.get("USERNAME"))
				.replace("{USECNNAME}",r.get("USECNNAME"));
				if(r.get("DBUSER")){
					newHtml=newHtml.replace("{DBUSER}",("<i class='fa fa-book'></i> 平台账号:"+r.get("DBUSER")+" ")||"");
				}else{
					newHtml=newHtml.replace("{DBUSER}","");
				}
				if(r.get("PHONE")){
					newHtml=newHtml.replace("{PHONE}",("<i class='fa fa-book'></i> 电话:"+r.get("PHONE")+" ")||"")
				}else{
					newHtml=newHtml.replace("{PHONE}","");
				}	
				if(r.get("REMARK")){
					newHtml=newHtml.replace("{REMARK}",("<i class='fa fa-book'></i> 工作描述:"+r.get("REMARK")+" ")||"")
				}else{
					newHtml=newHtml.replace("{REMARK}","");
				}	
				if(r.get("MAIL")){
					newHtml=newHtml.replace("{MAIL}",("<i class='fa fa-book'></i> 邮箱:"+r.get("MAIL")+" ")||"");
				}else{
					newHtml=newHtml.replace("{MAIL}","");
				}
			$("#teamuserinfo").append(newHtml);
		}
		$("#teamuserinfo .list-group-item").click( function() {
			$("#teamuserinfo .list-group-item").removeClass("active");
			$(this).addClass("active");
			var staffName=$(this).attr("USERNAME");
            for(var i=0;i<ds_teamUser.getCount();i++){
				var r=ds_teamUser.getAt(i);
				if(r.get('USERNAME')==staffName){
					ds_teamUser.curRecord=r;break;
				}
			}
			return false;
		});
 	}

    function buildTeamUserInfo(){
 		var showStaffInfoDialog=function(acttype){
  		$("#staffForm").empty();
  		var roleName = "select t.GROUPCODE,t.GROUPNAME from metagroup t where t.team_code = '{teamCode}'".replace('{teamCode}',objname);
		var formcfg = ({
			id : 'form',
			store : ds_teamUser,      
			containerId : 'staffForm',
			items : [ { type : 'text', label : '英文名',notNull:'N', fieldName : 'USERNAME', width : 220, isReadOnly:acttype=='edit'?'y':'n'},
				{ type : 'text', label : '中文名', notNull:'N',fieldName : 'USECNNAME', width : 220  },
				{ type : 'text', label : '联系电话', fieldName : 'PHONE', width : 220  },
				{ type : 'text', label : '邮箱', fieldName : 'MAIL', width : 220  },
				{ type : 'text', label : '平台账号', fieldName : 'DBUSER', width : 220  },
				{ type : 'combox', label : '角色',notNull:'N', storesql:roleName, fieldName : 'GROUPCODE', width : 220  },
				{ type : 'textarea', label : '备注', fieldName : 'REMARK', width : 420  } 
			],
			fieldChange:function(fieldName, newVal){
				var ds_metaMember = new AI.JsonStore({///租户成员表
					sql :"select USERNAME, USECNNAME, PASSWORD, REMARK, QQ, MSN, PHONE, MAIL, DBUSER, MD5PASS from METAUSER where USERNAME='"+newVal+"'",
					table:'METAUSER',
					key:'USERNAME'
				});
				if(fieldName==='USERNAME'){
					if(ds_metaMember.getCount()>0){
						ds_teamUser.curRecord.set("USERNAME",'')
                        $("#staffForm #USERNAME").val('');
                        alert("该英文名称已经存在,不能重复添加!");                       
					}
				}
				if(fieldName==='MAIL'){
					if(newVal.length!=0){
						var reg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
						if(!reg.test(newVal)){
							alert("对不起，您输入的邮箱格式不正确!(例如:example@xx.com)");
						}
					}else{
						alert("请输入邮箱地址！");
					}
				}
				if(fieldName==='PHONE'){
					if(newVal.length!=0){
						var reg=/^\d{11}$/;
						if(!reg.test(newVal)){
							alert("对不起，您输入的联系电话格式不正确!(11位数字)");
						}
					}else{
						alert("请输入联系电话！");
					}
				}
			}
		});
		gloableUserFormcfg = formcfg; 
		var from = new AI.Form(formcfg);
		$('#staffModal #dialog-ok').attr("acttype", acttype);
		$('#staffModal').modal({
			show : true
		});
   	}
	   //取消 
   	$("#staffModal #dialog-cancel").click(function() {
		for(var i=0;i<ds_teamUser.getCount();i++){
			var _r = ds_teamUser.getAt(i);
			if(_r.get("TMP_ADD")==='y'){
				ds_teamUser.remove(_r);
			}
		}
		ds_teamUser.cache.save = [];
	});

   	$("#staffModal #dialog-ok").click(function() {
		if ($('#staffModal #dialog-ok').attr('acttype') == 'add' || $('#staffModal #dialog-ok').attr('acttype') == 'edit') {
			   
			var items = gloableUserFormcfg.items;
			var keys = _.keys(ds_teamUser.curRecord.data);
			var _flag = true;
			var userName=ds_teamUser.curRecord.get("USERNAME");
			var memRecord = ds_teamUser.curRecord;	   
		    var ds_metaMember = new AI.JsonStore({///租户成员表
				sql :"select USERNAME, USECNNAME, PASSWORD, REMARK, QQ, MSN, PHONE, MAIL, DBUSER, MD5PASS from METAUSER where USERNAME='"+memRecord.get('USERNAME')+"'",
				table:'METAUSER',
				key:'USERNAME'
			}); 
			//修改了成员信息表单的非空验证如下2015-09-08
			for(var i=0;i<items.length;i++){
				var col = ds_teamUser.curRecord.get(items[i].fieldName);
				if((items[i].fieldName!='REMARK'&&items[i].fieldName!='PHONE'&&items[i].fieldName!='MAIL'&&items[i].fieldName!='DBUSER')&&(!col||col.length<1)&&(i<items.length)){
					_flag = false;
					alert(items[i].label+"不能为空！");
				}
				if(items[i].fieldName==='USERROLE'&&col==='角色'){
					_flag = false;
					alert("请选择角色类型！");
				}
				if(_flag===false){return;}
			}

		    ds_teamUser.curRecord.set('TMP_ADD','n');
			var groupname = new AI.JsonStore({///租户成员表
				sql :"SELECT GROUPNAME FROM metagroup WHERE team_code ='"+objname+"' AND groupcode='"+memRecord.get('GROUPCODE')+"'",
				table:'METAGROUP',
				key:'TEAM_CODE,GROUPCODE',
				pageSize : -1
			}); 
			if(groupname.getCount()>0){
				ds_teamUser.curRecord.set("USERROLE",groupname.getAt(0).get("GROUPNAME"));
			} 

			if($('#staffModal #dialog-ok').attr('acttype') == 'edit'){
				var r=ds_teamUser.curRecord; 
				var delete_sql="DELETE FROM metagroupuser WHERE groupcode='"+old_edit_groupcode+"' AND username='"+old_edit_username+"'";
				var insert_sql="INSERT INTO metagroupuser (USERNAME,GROUPCODE,USERROLE,REMARK) VALUES ('"+r.get('USERNAME')+"','"+r.get('GROUPCODE')+"','"+r.get('USERROLE')+"','"+r.get('REMARK')+"')";
				  		ai.executeSQL(delete_sql);                
				ai.executeSQL(insert_sql);
			}else if($('#staffModal #dialog-ok').attr('acttype') == 'add'){
				ds_teamUser.commit();
			}
			   
			buildTeamUserList();
			   ///同步人员身份信息
			if(ds_metaMember.getCount()==0){
				var userRecord=ds_metaMember.getNewRecord();
				userRecord.set('USERNAME',memRecord.get('USERNAME'));
				userRecord.set('USECNNAME',memRecord.get('USECNNAME'));
				userRecord.set('REMARK',memRecord.get('REMARK'));
				userRecord.set('PHONE',memRecord.get('PHONE'));
				userRecord.set('MAIL',memRecord.get('MAIL'));
				userRecord.set('DBUSER',memRecord.get('DBUSER'));
				var _URL="/"+contextPath+"/encrypt?password="+memRecord.get('USERNAME');
				var newpass=ai.remoteData(_URL,false);
				newpass = newpass.trim();
				userRecord.set('PASSWORD',newpass);
				userRecord.set('MD5PASS',newpass);
				ds_metaMember.add(userRecord);
				ds_metaMember.commit();
			  }else{
				var userRecord=ds_metaMember.getAt(0);
				userRecord.set('USERNAME',memRecord.get('USERNAME'));
				userRecord.set('USECNNAME',memRecord.get('USECNNAME'));
				userRecord.set('REMARK',memRecord.get('REMARK'));
				userRecord.set('PHONE',memRecord.get('PHONE'));
				userRecord.set('MAIL',memRecord.get('MAIL'));
				userRecord.set('DBUSER',memRecord.get('DBUSER'));
				ds_metaMember.commit(); 
			  };
		}
		$('#staffModal').modal("hide");
	});
	   
	 		//创建人员
    $("#createteamuser").click(function(){
    	var r=ds_teamUser.getNewRecord();
		r.set("USERNAME",'');
		r.set("USECNNAME",'');
		r.set("PHONE",'');
		r.set("MAIL",'');
		r.set("DBUSER",'');
		r.set("USERROLE",roleInfo['GROUPNAME']);
		r.set("REMARK",'');
		r.set('TMP_ADD','y');
		r.set("GROUPCODE",roleInfo['GROUPCODE']);
		ds_teamUser.add(r);
		ds_teamUser.curRecord=r;
		showStaffInfoDialog("add");
    });

    var updateTeamMgr = function() {
    	var recs = ai.getStoreData("select username from meta_team_role_user where team_code = '" + objname + "' and role_code = 'teamMgr'");
		var mgrs = "";
		for(var i in recs) {
			var username = recs[i].USERNAME;
			mgrs += username + ",";
		}
		if(!!mgrs) {
			mgrs = mgrs.substr(0, mgrs.length-1);
		}
		ai.executeSQL("update meta_team set team_mgr = '" + mgrs + "' where team_code = '" + objname + "'");
		buildMetaBaseInfo();
    };
	    
	//添加团队人员
	$("#addteamuser").click(function() {
		var afterSelectNewUser = function(rs) {
			for(var i=0;i<rs.length;i++){
				var r=ds_teamUser.getNewRecord();
				r.set("TEAM_CODE",objname);
				r.set("ROLE_CODE","default");
				r.set("USERNAME",rs[i].get('VALUES1'));
				r.set("REMARK",rs[i].get('VALUES2'));
				ds_teamUser.add(r);
			};
			ds_teamUser.commit();
			buildTeamUserList();
			alert("添加成功。点击分配人员角色按钮为新成员分配角色");
		};

		var selectSql = "select username VALUES1,usecnname values2,REMARK VALUES3 from metauser where username not in (select distinct username from meta_team_role_user where team_code = '" + objname + "')";
		var selBox=new SelectBox({sql:selectSql,callback:afterSelectNewUser});
		selBox.show();
	});

	var afterSelect=function(rs){
		var rolecode = teamRoleStore.curRecord.get('ROLE_CODE');
		for(var i=0;i<rs.length;i++){
			  var r=ds_teamUser.getNewRecord();
			  
			  ai.executeSQL("delete from meta_team_role_user where team_code = '" + objname + "' and username = '" + rs[i].get('VALUES1') + "' and role_code in('default','"+rolecode+"')");

			  r.set("TEAM_CODE",objname);
			  r.set("ROLE_CODE",rolecode);
			  r.set("USERNAME",rs[i].get('VALUES1'));
			  r.set("REMARK",rs[i].get('VALUES2'));
			  ds_teamUser.add(r);
		};
		ds_teamUser.commit();

		if(rolecode == "teamMgr") {
			updateTeamMgr();
		}
		buildTeamUserList();
	}; 

    //分配人员角色
    $("#selectteamuser").click(function(){
    	// var selSql="select username VALUES1,usecnname values2,REMARK VALUES3 from metauser where username not in (select username from metagroupuser a, metagroup b where a.groupcode = b.groupcode and b.team_code  ='"+objname+"')";

    	var selSql = "select username VALUES1,usecnname values2,REMARK VALUES3 from metauser where username in (select username from meta_team_role_user where team_code = '" + objname + "' and username not in (select username from meta_team_role_user where team_code = '" + objname + "' and role_code = '" + teamRoleStore.curRecord.get('ROLE_CODE') + "') group by username, role_code having role_code != '" + teamRoleStore.curRecord.get('ROLE_CODE') + "')";

 	   	var selBox=new SelectBox({sql:selSql,callback:afterSelect});
 	 	selBox.show();
    });
	    //删除
    $("#deleteteamuser").click(function(){
    	var r=ds_teamUser.curRecord;
	   	if(window.confirm("确定删除用户:"+r.get('USECNNAME')+"角色吗?")){
	   		var rolecode = teamRoleStore.curRecord.get('ROLE_CODE');
	   		var username = r.get('USERNAME');
	   		var remark = r.get('REMARK');

	   		if(rolecode == "all") {
	   			ai.executeSQL("delete from meta_team_role_user where team_code = '" + objname + "' and username = '" + username + "'");
				alert('成功删除');
				updateTeamMgr();
				buildTeamUserList();
				ds_teamUser.curRecord = "";
				return;
	   		}

			ai.executeSQL("delete from meta_team_role_user where team_code = '" + objname + "' and username = '" + username + "' and role_code = '" + rolecode + "'");
			alert('成功删除');
			if(rolecode == "teamMgr") {
				updateTeamMgr();
			}

			var userRec = ai.getStoreData("select * from meta_team_role_user where username = '" + username + "' and team_code = '" + objname + "'");
			if(userRec.length == 0) {
				var r=ds_teamUser.getNewRecord();
				r.set('TEAM_CODE', objname);
				r.set('ROLE_CODE', "default");
				r.set('USERNAME', username);
				r.set('REMARK', remark);
				ds_teamUser.add(r);
				ds_teamUser.commit();
			}
			buildTeamUserList();
			ds_teamUser.curRecord = "";
		}
    });
	    //修改
    $("#editteamuser").click(function(){
    	old_data=ds_teamUser.curRecord;
 		old_edit_groupcode=old_data.get("GROUPCODE");
 		old_edit_username=old_data.get("USERNAME");
	 	showStaffInfoDialog("edit"); 
    });
	 		
};

 	function buildDbList(){
 		$("#transDbInfo").empty();
 		myDBsql = "SELECT DBNAME,CNNAME,DBTYPE,JNDINAME,STATE,TEAM_CODE FROM data_trans_database WHERE team_code='{team_code}'";
 		ds_teamdb = new AI.JsonStore({///数据库列表
			sql : myDBsql.replace('{team_code}', objname),
			table:'DATA_TRANS_DATABASE',
			key:'TEAM_CODE,DBNAME,DBTYPE',
			pageSize : 20
		});
 		var config={
			bAutoWidth:true,
			store:ds_teamdb,
			pageSize: -1,
			containerId:'transDbInfo',
			nowrap:true,
			showcheck:false,
			columns:[
				{header: "数据库", width:80,dataIndex: 'DBNAME', sortable: true},
				{header: "中文名", width:120, dataIndex: 'CNNAME', sortable: true},
				{header: "本地别名", width:80, dataIndex: 'LOCALALIAS'},
				{header: "类型", width:74, dataIndex: 'DBTYPE'}
				// {header: "帐号名称", width:74, dataIndex: 'USERNAME'}
			],
			rowclick: buildUserList
		};
		dbListgrid =new AI.Grid(config);
		
 	}

 	function buildUserList(rownum){
 		$("#userInfo").show();
 		if(!rownum) {
 			return;
 		}
 		var dbname = ds_teamdb.getAt(rownum).get("DBNAME");
 		myDBUserSql = "SELECT DBNAME, TEAM_CODE, USERNAME, PASSWORD, URL FROM data_trans_database WHERE team_code='" + objname + "' and DBNAME = '" + dbname + "' and USERNAME is not null";
 		ds_dbuser = new AI.JsonStore({///用户
			sql : myDBUserSql,
			table:'DATA_TRANS_DATABASE',
			key:'USERNAME,DBNAME,TEAM_CODE',
			pageSize : 20
		});
		ds_dbuser.curRecord = ds_dbuser.getAt(0);

		var r = ds_dbuser.curRecord;
		$("#userInfo input").attr('disabled', 'true');
		if(!r) {
			$("#userInfo input").val('');
			$("#user-username").val('无用户');
		} else {
			$("#user-username").val(r.get("USERNAME"));
			$("#user-password").val(cryptoPassword(r.get("PASSWORD"), 'decrypt'));
			$("#user-url").val(r.get("URL"));
		}
 	}

 	var cryptoPassword = function(val, method) {
 		var pwd = '密码获取失败';
 		$.ajax({
			url:"/"+contextPath+"/crypto/" + method,
			data:{message: val},
			async: false,
			success:function(data, status){
				//alert(status);
				if(status=='success'){
					pwd = data.trim();
				}
			}
		});
		return pwd;
 	}
	 	
 	function buildDbInfo(){
 		var showDBInfoDialog = function(acttype){
		$("#dbForm").empty();
		var formcfg = ({
			id : 'form',
			store : ds_teamdb,
			containerId : 'dbForm',
			items : [
				{type : 'combox',editable:'N', label : '数据库', notNull:'N',fieldName : 'DBNAME', storesql : "select DBNAME,CNNAME from metadbcfg"},
				{type : 'text', label : '本地别名', fieldName : 'LOCALALIAS', width : 300}
			],
			fieldChange:function(fieldName, newVal) {
				if(newVal==''||newVal==null){
					alert("请选择数据库！");
					ds_teamdb.cache.save = [];
					ds_teamdb.cache.update = [];
					ds_teamdb.cache.remove = [];
					return;
				}
				if(fieldName==='DBNAME'){
					var store = new AI.JsonStore({///数据库列表
						sql : "select * from metadbcfg where dbname = '"+newVal+"'"
					});
					if(store.getCount()==0) return;
					var dbname = store.getAt(0).get('DBNAME');
					var cnname = store.getAt(0).get('CNNAME');
					var jndiname = store.getAt(0).get('JNDINAME');
					var dbusername=store.getAt(0).get('USERNAME');
					var dbtype = store.getAt(0).get('URL')?store.getAt(0).get('URL').split(':')[1]:'';
					var nondbname=false;
					for(var i =0 ; i< ds_teamdb.getCount(); i++){
						var r = ds_teamdb.getAt(i);
						if(dbname == r.get("LOGIC_DBNAME")&&objname==r.get("TEAM_CODE")){
							nondbname=true;
							break;
						}
					}

                    
					if(nondbname){
						alert("该团队下已经有该数据库,请重新选择！！");
						$("#dbForm #DBNAME").val('');
						ds_teamdb.cache.save = [];
					    ds_teamdb.cache.update = [];
					    ds_teamdb.cache.remove = [];
						return;
					}
					ds_teamdb.curRecord.set('CNNAME',cnname);
					ds_teamdb.curRecord.set('LOGIC_DBNAME',dbname);
					ds_teamdb.curRecord.set('DBNAME',objname + dbname);
					ds_teamdb.curRecord.set('JNDINAME',jndiname);
					ds_teamdb.curRecord.set('DBTYPE',dbtype);
					ds_teamdb.curRecord.set('TEAM_CODE',objname);
					
					var account;//以租户账号为租户数据库账号
					var resVal={};
					if(objDataStore.curRecord){
						resVal=objDataStore.curRecord.get('RES_CFG')?JSON.parse(objDataStore.curRecord.get('RES_CFG')):{};
					}
				    account=resVal.haddop_user&&resVal.haddop_user.length>0?resVal.haddop_user:null;
				    var rowname;
				    if(account){
						var isExistInDB = false;//租户数据库账号是否存在
						var metaedimdefStore = new AI.JsonStore({
							sql : "SELECT ROWCODE,ROWNAME,TYPE FROM METAEDIMDEF WHERE ROWCODE = '"+account+"' and DIMCODE='DIM_HADDOPDATABASE'",
							pageSize : -1,
							table : 'METAEDIMDEF',
						});
						for(var i=0;i<metaedimdefStore.getCount();i++){
							if(metaedimdefStore.getAt(i).get("TYPE")!=null){
								isExistInDB=true;break;
							}
						}
						if(!isExistInDB) account = null;
						rowname=metaedimdefStore.getAt(0).data["ROWNAME"];						
					}
					if(account&&account.length>0&&account!='hadoop平台'){
						$.ajax({
							url:"/"+contextPath+"/encrypt",
							data:{password:rowname},
							success:function(data, status){
								//alert(status);
								if(status=='success'){
									ds_teamdb.curRecord.set('USERNAME',account);
									ds_teamdb.curRecord.set('PASSWORD',data.trim());
								}
							}
						});
					}else{
						ds_teamdb.curRecord.set('USERNAME',"");
						ds_teamdb.curRecord.set('PASSWORD',"");
					}
					ds_teamdb.curRecord.set('USERNAME', null);
					ds_teamdb.curRecord.set('PASSWORD', null);
				}
			}
		});
		gloableDbCfg = formcfg;
		var from = new AI.Form(formcfg);
		$('#dbModal #db-dialog-ok').attr("acttype", acttype);
		$('#dbModal').modal({
			show : true,
			backdrop : 'static'
		});
	}

	$('#db-dialog-ok').on('click', function(){
	    var dbname=ds_teamdb.curRecord.get("DBNAME");	
	    if(dbname.trim()==''||dbname.trim()==null){
           alert("请选择数据库");
           ds_teamdb.cache.save = [];
		   ds_teamdb.cache.update = [];
		   ds_teamdb.cache.remove = [];
           return;
	    }
		ds_teamdb.commit();
		alert("数据库添加成功");
		ds_teamdb.select();
		// buildMetaTeamPerssion();
		$('#dbModal').modal("hide");
	});

	$('.db-dialog-cancel').on('click', function(){
		for(var i=0;i<ds_teamdb.getCount();i++){
			var _r = ds_teamdb.getAt(i);
			if(_r.get('TMP_ADD')==='y'){
				ds_teamdb.remove(_r);
			}
		}
		$('#dbModal').modal("hide");
	});
	 		
	};

	function buildAPITree() {
		$("#APITree").empty();

		var setting = {
			view: {selectedMulti: false},
			check: {enable: true},
			data: {simpleData: {enable: true}}
		};

		var teamPermission="select DISTINCT d.* FROM (	"+
			"SELECT DISTINCT a.APPLY id, 'root'  pId,A.APPLY NAME ,CASE WHEN B.FUNC_CODE IS NULL THEN 0 ELSE 1 END CHECKED ,'' FUNC_CODE "+
			"FROM proc_func_def_java a LEFT JOIN meta_team_func B "+
			 "ON A.FUNC_CODE=B.FUNC_CODE AND B.TEAM_CODE='{TEAMCODE}'  "+
			"UNION SELECT  B.MEMO id, CASE WHEN B.APPLY IS NULL THEN 'root' ELSE B.APPLY END pId,b.MEMO NAME ,CASE WHEN  "+
			"C.FUNC_CODE IS NULL THEN 0 ELSE 1 END CHECKED ,b.func_code FROM proc_func_def_java B  "+
			"LEFT JOIN meta_team_func C  "+
			"ON B.FUNC_CODE=C.FUNC_CODE AND C.TEAM_CODE='{TEAMCODE}') D  WHERE D.ID IS NOT NULL ORDER BY D.PID";

		var ds_api = new AI.JsonStore({
			sql : teamPermission.replace('{TEAMCODE}', objname).replace('{TEAMCODE}', objname),
			pageSize : -1
		});

		var buildZTree = function(models){
			var zNodesNew = [];
			if(models&&models.length>1){
				var n=0;
				for(var i=0;i<models.length;i++){
					var val = models[i];
					// if(val.ID == '5.数组&变量&逻辑') {
					// 	continue;
					// }
					zNodesNew.push({id:val.ID, pId:val.PID,name:val.ID,funCode:val.FUNC_CODE,checked:val.CHECKED==1?true:false});
				}
				$("#APITree").empty();
				$.fn.zTree.init($("#APITree"), setting, zNodesNew);
				var treeObj = $.fn.zTree.getZTreeObj("APITree");
				var nodes = treeObj.getNodes();
				for (var i = 0; i < nodes.length; i++) {
            		treeObj.setChkDisabled(nodes[i], true);
      			}
			}else{
				$("#APITree").append("找不到数据！");
			}
		};

		ds_api.on('dataload',function(){
			buildZTree(ds_api.root);
		});
		ds_api.select();

		$("#saveAPI").on('click',function() {
			var delSql="delete from meta_team_func WHERE team_code='"+objname+"'";
			ai.executeSQL(delSql);
			var sql ="select FUNC_CODE,team_code ,STATE from meta_team_func ";
			var store= new AI.JsonStore({
				sql:sql,
				pageSize:-1,
				table:'meta_team_func',
				key:'FUNC_CODE,team_code',
				dataSource:'METADB'
			});
				   	
			var zTree = $.fn.zTree.getZTreeObj("APITree");
			var nodes = zTree.getCheckedNodes();
			for (var i=0, l=nodes.length; i<l; i++) {
				var record=store.getNewRecord();
				if(nodes[i].funCode == null || nodes[i].funCode == '') continue;
				record.set("FUNC_CODE",nodes[i].funCode);
				record.set("team_code", objname);
				record.set('STATE','1');
				store.add(record);
			}
			var rs = store.commit(true);
			var rsJson = $.parseJSON(rs);
			alert(rsJson.msg);
		});
	}
	function buildTeamFlow(){
		var curFlowCode = '',ds_teamFlow,ds_teamFlowMember,formitems;
		function checkInputForm(fieldval){
			var result = true;
			for(var i=0;i<formitems.length;i++){
				if(formitems[i].notNull&&formitems[i].notNull.toUpperCase()=='N'&&!eval('fieldval.'+formitems[i].fieldName)){
					alert(formitems[i].label+'不能为空!');
					result=false;
					break;
				}
			};
			return result;
		};
		function afterEditOK(fieldval){
	    	if(!checkInputForm(fieldval)) return false;
		   	ds_teamFlowMember.commit();
		   	var xmlid = ds_teamFlowMember.curRecord.get('XMLID');
		   	var hmlobj = $("#team_flow_member li[xmlid='"+xmlid+"']");
		   	hmlobj.empty();
		   	hmlobj.append(getMemberHtml(null,ds_teamFlowMember.curRecord));
		   	$("#team_flow_member .pull-right").off('click').on('click',editMember);
		};
		function editMember(){
			var xmlid = $(this).attr('xmlid');
			ds_teamFlowMember.curRecord = ds_teamFlowMember.getRecordByKey(xmlid);
			formitems = [
			    { type : 'combox', label : '角色名称',isReadOnly:'y', notNull : 'N',fieldName : 'ROLENAME', width : 220,storesql:'select rolename from devwkflow_role where flowcode=\''+curFlowCode+'\''},
			    { type : 'combox', label : '默认成员',fieldName : 'DEFAULT_USERNAME', width : 220,	storesql:'select distinct t.username,q.usecnname from meta_team_role_user t join metauser q on t.username=q.username where team_code=\''+objname+'\''},
			    { type : 'checkbox', label : '成员信息',fieldName : 'USERNAME', storesql:'select distinct t.username,q.usecnname from meta_team_role_user t join metauser q on t.username=q.username where team_code=\''+objname+'\'',width : 220  }
			];
			var formcfg = ({
		    	title:'修改配置',
		    	lock:true,
		        id: 'formInfo',
		        store: ds_teamFlowMember,
		        containerId: 'baseInfoForm',
		        items: formitems
		    });
			ai.showDialogForm(formcfg,'',afterEditOK,null,'300px');
			$('input[type="checkbox"]').parent().parent().parent().css('margin-top','4px');
            $('input[type="checkbox"]').css({"vertical-align":"middle", "margin":"0px 4px 2px 0px"});
		};
		function getMemberHtml(store,r){
			var htmltpl ='<a class="thumb-sm pull-left m-r-sm" style="font-size:30px"> <span class="glyphicon glyphicon-user img-circle" aria-hidden="true"></span></a>'
				+ '<a class="clear"> <span class="pull-right" xmlid="{XMLID}"> <i class="glyphicon glyphicon-pencil"></i>编辑</span>  '
				+ '<strong class="block">{ROLENAME} {DEFAULT_USERNAME} </strong> '
				+ '<small> <i class="icon-users icon text-warning"></i>成员信息:{USERNAME}</small></a>';
			var html = '';
			if(!r&&store) {
				if(store.getCount()>0){
					htmltpl = '<li class="list-group-item"  xmlid="{XMLID}" style="min-height: 66px">'+htmltpl			+'</li>';
					for(var i = 0;i<store.getCount();i++){
						var r = store.getAt(i);
						var defaultUser = r.get("DEFAULT_USERNAME");
						var users = r.get("USERNAME");
						html += htmltpl.replaceAll("{XMLID}",r.get("XMLID") )
							.replaceAll("{ROLENAME}",r.get("ROLENAME")).replace("{DEFAULT_USERNAME}",defaultUser?(','+defaultUser):'')
							.replace("{USERNAME}",users?users:'<span style="color:red">未设置</span>');
					};					
				}else{
					html = '<span class = "empty">无相关数据</span>';
				}
			}else{
				var defaultUser = r.get("DEFAULT_USERNAME");
				var users = r.get("USERNAME");
				html = htmltpl.replaceAll("{XMLID}",r.get("XMLID") )
					.replaceAll("{ROLENAME}",r.get("ROLENAME")).replace("{DEFAULT_USERNAME}",defaultUser?(','+defaultUser):'')
					.replace("{USERNAME}",users?users:'<span style="color:red">未设置</span>');
			}
			return html;
		};	
		function initTeamFlow(){
			function initTeamFlowMember(v){
		  		var flowcode = v.get('FLOWCODE');
		 		ds_teamFlowMember = new AI.JsonStore({
		 			sql:"select * from meta_team_flow_role t where t.team_code='"+objname+"' and t.flowcode='"+flowcode+"' and rolepointtype='团队定义'",
		 			table:'META_TEAM_FLOW_ROLE',
		 			key:'XMLID'
		 		});
			  	$('#team_flow_member').empty();
				var html = getMemberHtml(ds_teamFlowMember,null);
				$("#team_flow_member").append(html);
				$("#team_flow_member .pull-right").off('click').on('click',editMember);
	  		};
	 		ds_teamFlow = new AI.JsonStore({
	 			sql:"select t.team_code,t.flowcode,q.flowname,t.state_date,t.xmlid from meta_team_flow t join devwkflow q on t.flowcode=q.flowcode where t.team_code='"+objname+"'",
	 			table:'meta_team_flow',
	 			key:'TEAM_CODE,FLOWCODE'
	 		});
	 		var html = '';
	 		if(ds_teamFlow.getCount()>0){
		 		var htmltpl='<a flowcode="{flowcode}" class="list-group-item"> <i class="icon-users icon text-warning"></i> {flowname}, {flowcode} </a>';
		 		for (var i = 0; i < ds_teamFlow.getCount(); i++) {
					var r=ds_teamFlow.getAt(i);
					html += htmltpl.replaceAll("{flowcode}",r.get('FLOWCODE')).replaceAll("{flowname}",r.get('FLOWNAME'));
				};
			}else{
				html = '<span class = "empty">该租户无流程数据</span>';
			}
			$('#team_flow_info').empty();
			$("#team_flow_info").append(html);
			$("#team_flow_info .list-group-item").click( function() {
				$("#team_flow_info .list-group-item").removeClass("active");
				$(this).addClass("active");
				curFlowCode=$(this).attr("flowcode");
				var curRecord=ds_teamFlow.getRecordByKey(objname+","+curFlowCode);
				initTeamFlowMember(curRecord);
				return false;
			});
	 		if(ds_teamFlow.getCount()>0) $("#team_flow_info .list-group-item")[0].click();
	  	};
	  	initTeamFlow();
	}
	 	 
	buildMetaBaseInfo();
	buildTeamRoleList();
	buildTeamUserList();
	buildTeamUserInfo();
	buildDbList();
	buildDbInfo();
	TeamPerMission.init({teamcode:objname, containerId:'metaTeamPerssionInfo', editable: isMgr});
	// buildTabList();
	buildAPITree();
	buildTeamFlow();
	 	//团队信息编辑
	$("#editObjInfo").click(function(){
		if(!teamXmlid) {
			var rec = ai.getStoreData("select xmlid from meta_team where team_code = '" + objname + "'")[0];
			if(!rec) {
				alert("meta_team不存在该团队信息！");
				return;
			}
			teamXmlid = rec.XMLID;
		}
		metasoft.editMetaObjBaseInfo({objtype:objtype,objid:teamXmlid,storeAtMetaObj:'n',aftSave:buildMetaBaseInfo});
		$("#TEAM_CODE").attr("disabled",true);
		$("#TEAM_NAME").attr("disabled",true);
		$("#TEAM_TYPE").attr("disabled",true);
		$("#STATE").attr("disabled",true);
    });
    $("#saveMetaPerssionInfo").click(function(){
    		if(!confirm("是否确认保存变更后的权限信息?")) return;
    		teamperssionstore.select("select * from metateampermission where 1=2");
    		 $(".ai-treegrid-body-check:checked","#metaTeamPerssionInfo").each(function(){
    		 		var _dbname = $(this).attr("DBNAME");
    		 		var _ruleCode = $(this).attr("RULECODE");
    		 		var _strutsKeyValue = _dbname+","+_ruleCode;
    		 		var teamperssionRecord = teamperssionstore.getNewRecord();
    		 		var dbStructRecord = dbStrutStore.getRecordByKey(_strutsKeyValue);
    		 		for(var i = 0 ;i <dbStrutStore.fields.length;i++){
    		 			teamperssionRecord.set(dbStrutStore.fields[i].name,dbStructRecord.get(dbStrutStore.fields[i].name));
    		 		}
    		 		teamperssionRecord.set("TEAM_CODE",objname);	
    		 		var tempFuncId="";
    		 		$(this).parent().parent().find("input:checkbox[name='FUNC_ID']:checked").each(function(i){
    		 				if(0==i){
    		 					tempFuncId = $(this).val();
    		 				}else{
    		 					tempFuncId += (","+$(this).val());
    		 				}
    		 		});
    		 		teamperssionRecord.set("FUNC_ID",tempFuncId);
    		 		
    		 		var tempGroupCode="";
    		 		$(this).parent().parent().find("input:checkbox[name='OWNER_GROUPCODE']:checked").each(function(i){
    		 				if(0==i){
    		 					tempGroupCode = $(this).val();
    		 				}else{
    		 					tempGroupCode += (","+$(this).val());
    		 				}
    		 		});
    		 		teamperssionRecord.set("OWNER_GROUPCODE",tempGroupCode);
    		 		teamperssionstore.add(teamperssionRecord);
    		 });	
    		 //直接删除
				ai.executeSQL("delete from metateampermission where team_code='"+objname+"'");
    		teamperssionstore.cache.update=[];
    		var rs = teamperssionstore.commit(true);
        var rsJson = $.parseJSON(rs);
        alert(rsJson.msg);
    		
    });
    $("#resetTeamPermission").click(function(){
    	 TeamPerMission.reset();
    });
    
    if(!isMgr) {
    	$("#teamrole-toolbar button").attr("disabled",true).css("background-color", "#c9bfbf").css("border-color", "#c9bfbf");
    	$("#teamPermission-toolbar button").attr("disabled",true).css("background-color", "#c9bfbf").css("border-color", "#c9bfbf");
    	$("#editObjInfo").attr("disabled",true).css("background-color", "#c9bfbf").css("border-color", "#c9bfbf");
    } else {
    	$("#teamrole-toolbar button").attr("disabled",null);
    	$("#teamPermission-toolbar button").attr("disabled",null);
    	$("#editObjInfo").attr("disabled",null);
    }
});
</script>
</head>
<body class="">
	<div class="container-fluid">
		<div class="row" id="teamInfo">
			<div class="col-sm-3" style="padding-left: 1px; padding-right: 1px">
				<h5> 团队基本信息<small id='tip'> </small> </h5>
				<section class="panel panel-info portlet-item" style="opacity: 1; z-index: 0;">
					<header class="panel-heading"> 详细信息 </header>
					<div class="panel-body "
						style="width: 100%; height: auto; padding: 0px" id="teambaseinfo">

					</div>
					<footer class="panel-footer"  > <a href="#" id="editObjInfo" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>编辑</a>  </footer>
				</section>
			</div>
			<div class="col-sm-9">
				<h5><span id="funaction">团队分项详细信息</span></h5>
				<section class="panel panel-info">
					<header class="panel-heading">
						<span class="hidden-sm"> &nbsp; </span> <span id="taskname"
							style="float: left">详细信息</span>
						<ul class="nav nav-tabs pull-right">
							<li class="active"><a href="#tab0" data-toggle="tab"> <i class="fa fa-comments text-muted"> </i> 团队成员信息 </a></li>
							<li class=""><a href="#tab1" data-toggle="tab"> <i class="fa fa-comments text-muted"> </i> 团队数据库信息 </a></li>
							<li class=""><a href="#tab2" data-toggle="tab"> <i class="fa fa-user text-muted"> </i> 团队权限信息 </a></li>
							<li class="" style="display:none"><a href="#tab3" data-toggle="tab"> <i class="fa fa-user text-muted"> </i> 表授权信息 </a></li>
							<li class=""><a href="#tab4" data-toggle="tab"> <i class="fa fa-user text-muted"> </i> API授权信息 </a></li>
							<li class=""><a href="#tab5" data-toggle="tab"> <i class="fa fa-user text-muted"> </i> 团队流程信息 </a></li>
						</ul>
					</header>
				</selection>
				<div class="panel-body">
					<div class="tab-content">
						<div class="tab-pane active" id="tab0">
							<div class="row">
							  <div class="col-md-4">
							  	<div class="panel panel-default">
							  			<div class="panel-heading"> <span class="font-thin m-l-md m-t">团队角色</span> </div>
							  	       <div class="panel-body" >
							  	       	    <div class="list-group no-radius no-border no-bg m-t-n-xxs m-b-none auto" id="teamrolelist">
							  	       	  </div>
							  	       	</div>
							  	      <div class="panel-footer no-border">
													<!-- <a id="addTeamRole" class="btn btn-sm btn-primary"> <i class="fa fa-css3"> </i> 创建 </a> <a id="delTeamRole" class="btn btn-sm btn-danger "> <i class="fa fa-times"> </i> 删除
													</a> <a id="editTeamRole" class="btn btn-sm btn-primary"> <i class="fa fa-css3"> </i> 修改 </a> -->
									  </div>
									  </div>
							  </div>
							  <div class="col-md-8">
								<div class='toolbar' id='teamrole-toolbar'>
									<button id="addteamuser" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>添加团队成员</button>
									<button id="selectteamuser" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>分配人员角色</button>
									<button id="deleteteamuser" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>删除</button>
									<button id="editteamuser" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>修改</button>
								</div>
								<div class="panel-body" id="teamuserinfo"></div>
							</div>
						</div>
						</div>
						<div class="tab-pane" id="tab1">
							<div class='toolbar'>
								 
								<!-- <button id="selectDbInfo" class="btn btn-danger  btn-xs " enabled=""  <i class="glyphicon glyphicon-user"></i>选择库</button>
								<button id="deleteDbInfo" class="btn btn-danger  btn-xs " enabled=""  <i class="glyphicon glyphicon-user"></i>删除库权限</button> -->
								<!-- <button id="userDbInfo" class="btn btn-danger  btn-xs " enabled=""  <i class="glyphicon glyphicon-user"></i>数据库用户权限</button> -->
							</div>
							<div class="panel-body" id="transDbInfo"></div>
							<div class='toolbar'>
								<!-- <button id="addUser" class="btn btn-danger  btn-xs " enabled=""  <i class="glyphicon glyphicon-user"></i>增加用户</button>
								<button id="deleteUser" class="btn btn-danger  btn-xs " enabled=""  <i class="glyphicon glyphicon-user"></i>删除用户</button> -->
								<!-- <button id="syncUser" class="btn btn-danger  btn-xs " enabled=""  <i class="glyphicon glyphicon-user"></i>指定运行账号</button> -->
							</div>
							<div class="panel-body col-sm-6" id="userInfo" style="display:none">
								<section class="panel panel-info">
									<header class="panel-heading">
										<span class="hidden-sm"> &nbsp; </span><span id="taskname" style="float: left">数据库用户信息:</span>
									</header>
									<fieldset> 
										<table class="table">
											<tbody >
												<tr><th class="strong w-80px">用户名</th><td>
													<input type='text' id='user-username' style="height: 90%; width: 98%"/>
												</td></tr>
												<tr><th class="strong w-80px">密码</th><td>
													<input type='text' id='user-password' style="height: 90%; width: 98%"/>
												</td></tr>
												<tr><th class="strong w-80px">URL</th><td>
													<input type='text' id='user-url' style="height: 90%; width: 98%"/>
												</td></tr>
											</tbody>
										</table>
									</fieldset>
									<!-- <footer class="panel-footer"  > <a href="#" id="editUserInfo" class="btn btn-danger  btn-xs " enabled=""  <i class="glyphicon glyphicon-user"></i>确认修改</a>  </footer> -->
								</section>
							</div>
						</div>
						<div class="tab-pane" id="tab2">
								<div class='toolbar' id="teamPermission-toolbar">
									<button id="resetTeamPermission" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>重置</button>
									<button id="saveMetaPerssionInfo" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>保存</button>
								</div>
								<div class="panel-body" id="metaTeamPerssionInfo"></div>
						</div>
						<div class="tab-pane" id="tab3">
								<div class='toolbar'>
									 
									<button id="selectTab" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>添加表</button>
									<button id="deleteTab" class="btn btn-danger  btn-xs " enabled="" > <i class="glyphicon glyphicon-user"></i>删除表权限</button>
								</div>
								<div class="panel-body" id="tabInfo"></div>
						</div>
						<div class="tab-pane" id="tab4">
							<section class="panel panel-default">
								<div class='toolbar'>
									<!-- <button id="saveAPI" class="btn btn-danger  btn-xs " enabled="">  <i class="glyphicon glyphicon-user"></i>保存</button> -->
								</div>
								<div class="panel-body slim-scroll"><ul id="APITree" class="ztree"></ul></div>
							</section>
						</div>
						<div class="tab-pane" id="tab5">
							<div class="col-md-4">
								<div class="panel panel-default">
									<div class="panel-heading"> <span class="font-thin m-l-md m-t">团队流程</span> </div>
						  	        <div class="panel-body" id="team_flow_info" style="overflow-y:auto; max-height:400px">
						  	       	</div>
						  	    </div>
							</div>
							<div class="col-md-8">
								<div class="panel-body" id="team_flow_member" style="overflow-y:auto; height:200px"></div>
							</div>
						</div>
					</div>	
				</div>		
			</div>	
		<div>
	</div>
	<div id="staffModal" class="modal fade">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
					</button>
					<h4 class="modal-title">人员信息</h4>
				</div>
				<div class="modal-body" id="staffForm"></div>
				<div class="modal-footer">
					<button id="dialog-cancel" type="button" class="btn btn-default" data-dismiss="modal">取消</button>
					<button id="dialog-ok" type="button" class="btn btn-primary">确认</button>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal -->	
	<div id="dbModal" class="modal fade">
		<div class="modal-dialog" style="z-index: 10000;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close db-dialog-cancel">
						<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
					</button>
					<h4 class="modal-title">数据库信息</h4>
				</div>
				<div class="modal-body" id="dbForm"></div>
				<div class="modal-footer">
					<button type="button" class="btn btn-default db-dialog-cancel">取消</button>
					<button id="db-dialog-ok" type="button" class="btn btn-primary">确认</button>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal -->
</body>
</html>		